package com.example.demo41multiusers.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService us1() {
        return new InMemoryUserDetailsManager(User.withUsername("wangnian").password("{noop}123").roles("admin").build());
    }

    @Bean
    UserDetailsService us2() {
        return new InMemoryUserDetailsManager(User.withUsername("zhangsan").password("{noop}123").roles("user").build());
    }

    /**
     * ProviderManager 维护了一个 AuthenticationProvider 的集合，到时候认证时会遍历所有的 AuthenticationProvider，
     * 并调用它的 authenticate 方法进行认证。
     * 所以我们自定义的 ProviderManager 并将两个不同用户数据源的 AuthenticationProvider 添加到  AuthenticationProvider 的集合中即可。
     */
    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        DaoAuthenticationProvider provider1 = new DaoAuthenticationProvider();
        provider1.setUserDetailsService(us1());
        DaoAuthenticationProvider provider2 = new DaoAuthenticationProvider();
        provider2.setUserDetailsService(us2());
        return new ProviderManager(provider1,provider2);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll()
                .and().csrf().disable();
    }

    /**
     * 配置 /hello 不走过滤器，将会生成一个 没有 Security 过滤器的过滤器链(DefaultSecurityFilterChain)
     * 这样的话就会直接走 Web Filter
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/hello");
    }

}
